<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat Page</title>
    <style>
        /* Reset and base styles */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            font-size: 16px;
            color: #333;
            background-color: #fff;
        }

        /* Chat container styles */
        .chat-container {
            display: flex;
            flex-direction: column;
            box-sizing: border-box;
            height: 100vh;
            font-size: 16px;
            background-color: #fff;
        }

        .nav-bar {
            height: 44px;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            border-bottom: 1px solid #e7e7e7;
        }

        .nav-bar-title {
            font-weight: 500;
        }

        .nav-bar-back {
            position: absolute;
            left: 15px;
            font-size: 20px;
        }

        /* 内容区域 */
        .content {
            flex: 1;
            overflow-y: auto;
            padding: 16px 12px;
        }

        .messages {
            display: flex;
            flex-direction: column;
            gap: 16px;
            padding: 16px 12px;
        }

        .time {
            display: flex;
            justify-content: center;
            align-items: flex-end;
            height: 28px;
            color: rgba(0, 0, 0, 0.4);
            font-size: 12px;
            line-height: 20px;
        }

        .message-area {
            display: flex;
            align-items: flex-start;
            gap: 8px;
        }

        .message {
            position: relative;
            box-sizing: border-box;
            max-width: 255px;
            padding: 12px;
            font-size: 14px;
            line-height: 22px;
            word-break: break-word;
        }

        .message.self {
            border-radius: 12px 0 12px 12px;
            margin-left: auto;
            background-color: #d9e1ff;
        }

        .message.other {
            border-radius: 0 12px 12px 12px;
            background-color: #f3f3f3;
        }

        .loading {
            position: absolute;
            right: calc(100% + 8px);
            top: 50%;
            transform: translateY(-50%);
            width: 16px;
            height: 16px;
            border: 2px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top-color: #000;
            animation: spin 1s linear infinite;
        }
        .chat-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            position: relative;
            overflow: hidden;
        }
        @keyframes spin {
            to { transform: translateY(-50%) rotate(360deg); }
        }

        .block {
            height: calc(env(safe-area-inset-bottom) + 65px);
        }

        .bottom {
            position: sticky; /* 可选 */
            bottom: 0;
            left: 0;
            width: 100%;
            padding: 12px;
            background-color: #ffffff;
            border-top: 1px solid #e7e7e7;
            display: flex;
            align-items: center;
            gap: 12px;
            z-index: 10;
        }

        .input {
            box-sizing: border-box;
            flex-grow: 1;
            height: 40px;
            padding: 8px 16px;
            border-radius: 20px;
            border: 1px solid #dcdcdc;
            background: #f3f3f3;
            line-height: 24px;
        }

        .input > input {
            width: 100%;
            height: 24px;
            line-height: 24px;
            border: none;
            background: transparent;
            outline: none;
            font-size: 14px;
        }

        .send {
            width: 64px !important;
            margin: 0;
            font-weight: normal !important;
            padding: 8px 12px;
            background-color: #0066ff;
            color: white;
            border: none;
            border-radius: 20px;
            font-size: 14px;
            cursor: pointer;
        }

        .send:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: #eee;
            overflow: hidden;
        }

        .avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .chat-container {
            display: flex;
            flex-direction: row;
            height: 100vh;
        }


        /* 左侧用户列表样式 */
        .user-list {
            width: 280px;
            border-right: 1px solid #e7e7e7;
            display: flex;
            flex-direction: column;
            background-color: #f9f9f9;
            height: 100vh; /* 固定高度 */
            overflow-y: auto; /* 支持滚动 */
        }

        .user-search {
            height: 56px;
            display: flex;
            align-items: center;
            padding: 0 12px;
            border-bottom: 1px solid #e7e7e7;
            background-color: #fff;
        }

        .user-search input {
            flex: 1;
            height: 36px;
            padding: 0 12px;
            border-radius: 18px;
            border: 1px solid #dcdcdc;
            background-color: #f3f3f3;
            font-size: 14px;
            outline: none;
        }

        .add-user-btn {
            margin-left: 8px;
            width: 56px;
            height: 36px;
            background-color: #0066ff;
            color: white;
            border: none;
            border-radius: 20px;
            font-size: 14px;
            cursor: pointer;
        }

        .add-user-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .user-list-container {
            flex: 1;
            overflow-y: auto;
            padding: 8px;
        }

        .user-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.2s ease;
        }

        .user-item:hover {
            background-color: #ececec;
        }

        .user-item.active {
            background-color: #d9e1ff;
        }

    </style>
</head>
<body>
<div class="chat-container">
    <!-- 左侧用户列表 -->
    <div class="user-list">
        <div class="user-search">
            <input type="text" id="user-search-input" placeholder="搜索或添加用户...">
            <button class="add-user-btn">添加</button>
        </div>
        <div class="user-list-container" id="user-list">
            <!-- 用户列表项会动态插入这里 -->
        </div>
    </div>

    <!-- 右侧聊天内容 -->
    <div class="chat-content">
        <div class="nav-bar">
            <div class="nav-bar-title" id="chat-title"></div>
        </div>

        <div class="content" id="message-container">
            <div class="messages" id="messages">
                <!-- Messages will be inserted here by JavaScript -->
            </div>
            <div id="bottom"></div>
        </div>

        <!-- 底部输入栏 -->
        <div class="block" id="block"></div>
        <div class="bottom" id="bottom-bar">
            <div class="input">
                <input
                        id="message-input"
                        type="text"
                        placeholder="请输入"
                        style="color: rgba(0, 0, 0, 0.4)"
                />
            </div>
            <button class="send" id="send-button" disabled>发送</button>
        </div>
    </div>
</div>

    <script>
    // Formatting functions from WXS
    const utils = {
        /** 将数字补足2位 */
        formatNum: function(num) {
            return num < 10 ? '0' + num : num;
        },

        /** 格式化时间 */
        formatTime: function(time) {
            var date = new Date(time);
            var now = new Date();
            var Y = date.getFullYear(),
                M = date.getMonth() + 1,
                D = date.getDate(),
                h = date.getHours(),
                m = date.getMinutes();
            var Y0 = now.getFullYear(),
                M0 = now.getMonth() + 1,
                D0 = now.getDate();
            if (Y === Y0) {
                if (M === M0 && D === D0) return '今天 ' + this.formatNum(h) + ':' + this.formatNum(m);
                if (M === M0 && D === D0 - 1) return '昨天 ' + this.formatNum(h) + ':' + this.formatNum(m);
                return M + '月' + D + '日 ' + this.formatNum(h) + ':' + this.formatNum(m);
            }
            return Y + '年' + M + '月' + D + '日 ' + this.formatNum(h) + ':' + this.formatNum(m);
        }
    };

    // Main application logic from index.js
    class ChatPage {
        constructor() {
            this.data = {
                myAvatar: '/static/chat/avatar.png', // 自己的头像
                userId: null, // 对方userId
                avatar: '', // 对方头像
                name: '', // 对方昵称
                messages: [], // 消息列表 { messageId, from, content, time, read }
                input: '', // 输入框内容
                keyboardHeight: 0, // 键盘当前高度(px)
                socket: null // WebSocket connection
            };

            this.initElements();
            this.bindEvents();
            this.initSocket();
            this.initUserList();
        }
        //聊天页面
        initUserList() {
            this.elements.userSearchInput = document.getElementById('user-search-input');
            this.elements.userListContainer = document.getElementById('user-list');

            // 模拟用户数据
            this.userData = {
                users: [
                    { id: '1', name: '张三', avatar: 'https://via.placeholder.com/36' },
                    { id: '2', name: '李四', avatar: 'https://via.placeholder.com/36' },
                    { id: '3', name: '王五', avatar: 'https://via.placeholder.com/36' }
                ],
                selectedUserId: null
            };

            this.renderUserList();

            // 绑定事件
            this.elements.userSearchInput.addEventListener('input', (e) => {
                this.filterUsers(e.target.value);
            });

            this.elements.userListContainer.addEventListener('click', (e) => {
                const userId = e.target.closest('.user-item')?.dataset.userId;
                if (userId && userId !== this.userData.selectedUserId) {
                    this.selectUser(userId);
                }
            });

            this.elements.addUserBtn = document.querySelector('.add-user-btn');
            this.elements.addUserBtn.addEventListener('click', () => {
                const username = this.elements.userSearchInput.value.trim();
                if (username) {
                    this.addUser(username);
                }
            });
        }

        renderUserList(filteredUsers = this.userData.users) {
            this.elements.userListContainer.innerHTML = '';

            filteredUsers.forEach(user => {
                const userDiv = document.createElement('div');
                userDiv.className = 'user-item';
                userDiv.dataset.userId = user.id;

                userDiv.innerHTML = `                <div class="avatar">
                    <img src="${user.avatar}" alt="${user.name}">
                </div>
                <div class="user-name">${user.name}</div>
            `;

                this.elements.userListContainer.appendChild(userDiv);
            });
        }

        filterUsers(query) {
            if (!query) {
                this.renderUserList();
                return;
            }

            const filtered = this.userData.users.filter(user =>
                user.name.toLowerCase().includes(query.toLowerCase())
            );
            this.renderUserList(filtered);
        }

        addUser(name) {
            const newUser = {
                id: Date.now().toString(),
                name,
                avatar: 'https://via.placeholder.com/36'
            };

            this.userData.users.push(newUser);
            this.elements.userSearchInput.value = '';
            this.selectUser(newUser.id);
            this.renderUserList();
        }

        selectUser(userId) {
            this.userData.selectedUserId = userId;
            const selectedUser = this.userData.users.find(u => u.id === userId);

            // 更新聊天界面
            this.update({
                userId: selectedUser.id,
                avatar: selectedUser.avatar,
                name: selectedUser.name,
                messages: [] // 清空消息记录，实际应从服务器获取
            });

            // 更新用户列表高亮状态
            Array.from(this.elements.userListContainer.children).forEach(item => {
                item.classList.toggle('active', item.dataset.userId === userId);
            });
        }
        //聊天页面

        initElements() {
            this.elements = {
                title: document.getElementById('chat-title'),
                messageContainer: document.getElementById('message-container'),
                messages: document.getElementById('messages'),
                block: document.getElementById('block'),
                bottomBar: document.getElementById('bottom-bar'),
                input: document.getElementById('message-input'),
                sendButton: document.getElementById('send-button')
            };
        }

        bindEvents() {
            // Input events
            this.elements.input.addEventListener('input', (e) => {
                this.setData({ input: e.target.value });
                this.elements.sendButton.disabled = !e.target.value;
            });

            // Send message events
            this.elements.sendButton.addEventListener('click', () => this.sendMessage());
            this.elements.input.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    this.sendMessage();
                }
            });

            // Keyboard events (simplified for web)
            window.addEventListener('resize', () => {
                // In a real implementation, you'd detect keyboard appearance differently
                const isMobile = window.innerWidth <= 768;
                const newHeight = isMobile ? (window.innerHeight < 500 ? 300 : 200) : 0;
                if (newHeight !== this.data.keyboardHeight) {
                    this.setData({ keyboardHeight: newHeight });
                    this.updateLayout();
                }
            });
        }

        initSocket() {
            // Simulate WebSocket connection
            this.data.socket = {
                send: (data) => {
                    console.log('WebSocket send:', data);
                    // Simulate response after 1 second
                    setTimeout(() => {
                        const msg = JSON.parse(data);
                        if (msg.type === 'message') {
                            this.handleReceivedMessage({
                                messageId: Date.now(),
                                from: 1, // Simulate other user
                                content: `Reply to: ${msg.data.content}`,
                                time: Date.now(),
                                read: true
                            });
                        }
                    }, 1000);
                }
            };
        }

        setData(newData) {
            Object.assign(this.data, newData);
            this.updateView();
        }

        updateView() {
            // Update title
            if (this.data.name) {
                this.elements.title.textContent = this.data.name;
            }

            // Update messages
            this.renderMessages();
        }

        updateLayout() {
            this.elements.block.style.marginBottom = `${this.data.keyboardHeight}px`;
            this.elements.bottomBar.style.marginBottom = `${this.data.keyboardHeight}px`;
            this.scrollToBottom();
        }

        renderMessages() {
            this.elements.messages.innerHTML = '';

            this.data.messages.forEach((item, index) => {
                // Add time separator if needed
                if (index === 0 || item.time - this.data.messages[index - 1].time > 120000) {
                    const timeDiv = document.createElement('div');
                    timeDiv.className = 'time';
                    timeDiv.textContent = utils.formatTime(item.time);
                    this.elements.messages.appendChild(timeDiv);
                }

                // Create message area
                const messageArea = document.createElement('div');
                messageArea.className = 'message-area';

                if (item.from === 0) {
                    // Self message
                    const messageDiv = document.createElement('div');
                    messageDiv.className = 'message self';

                    const contentSpan = document.createElement('span');
                    contentSpan.textContent = item.content;
                    messageDiv.appendChild(contentSpan);

                    if (item.messageId === null) {
                        const loadingDiv = document.createElement('div');
                        loadingDiv.className = 'loading';
                        messageDiv.appendChild(loadingDiv);
                    }

                    messageArea.appendChild(messageDiv);

                    const avatarDiv = document.createElement('div');
                    avatarDiv.className = 'avatar';
                    const avatarImg = document.createElement('img');
                    avatarImg.src = this.data.myAvatar;
                    avatarDiv.appendChild(avatarImg);
                    messageArea.appendChild(avatarDiv);
                } else {
                    // Other message
                    const avatarDiv = document.createElement('div');
                    avatarDiv.className = 'avatar';
                    const avatarImg = document.createElement('img');
                    avatarImg.src = this.data.avatar || 'https://via.placeholder.com/36';
                    avatarDiv.appendChild(avatarImg);
                    messageArea.appendChild(avatarDiv);

                    const messageDiv = document.createElement('div');
                    messageDiv.className = 'message other';

                    const contentSpan = document.createElement('span');
                    contentSpan.textContent = item.content;
                    messageDiv.appendChild(contentSpan);

                    messageArea.appendChild(messageDiv);
                }

                this.elements.messages.appendChild(messageArea);
            });

            this.scrollToBottom();
        }

        scrollToBottom() {
            setTimeout(() => {
                this.elements.messageContainer.scrollTop = this.elements.messageContainer.scrollHeight;
            }, 50);
        }

        update({ userId, avatar, name, messages }) {
            this.setData({ userId, avatar, name, messages: [...messages] });
            this.scrollToBottom();
        }

        sendMessage() {
            const { userId, messages, input: content } = this.data;
            if (!content) return;

            const message = {
                messageId: null,
                from: 0,
                content,
                time: Date.now(),
                read: true
            };

            messages.push(message);
            this.setData({ input: '', messages });
            this.elements.input.value = '';
            this.elements.sendButton.disabled = true;

            if (this.data.socket) {
                this.data.socket.send(JSON.stringify({
                    type: 'message',
                    data: { userId, content }
                }));
            }

            this.scrollToBottom();
        }

        handleReceivedMessage(message) {
            const messages = [...this.data.messages];

            // Update pending message if exists
            const pendingIndex = messages.findIndex(m => m.messageId === null && m.from === 0);
            if (pendingIndex !== -1) {
                messages[pendingIndex] = {
                    ...messages[pendingIndex],
                    messageId: Date.now()
                };
            }

            messages.push(message);
            this.setData({ messages });
        }
    }

    // Initialize the chat page when DOM is loaded
    document.addEventListener('DOMContentLoaded', () => {
        const chatPage = new ChatPage();

        // Simulate initial data load
        setTimeout(() => {
            chatPage.update({
                userId: '123',
                avatar: 'https://via.placeholder.com/36',
                name: '聊天用户',
                messages: [
                    {
                        messageId: 1,
                        from: 1,
                        content: '你好！',
                        time: Date.now() - 3600000,
                        read: true
                    },
                    {
                        messageId: 2,
                        from: 0,
                        content: '你好，有什么可以帮您的吗？',
                        time: Date.now() - 1800000,
                        read: true
                    }
                ]
            });
        }, 500);

        // Make chatPage available globally for debugging
        window.chatPage = chatPage;
    });
</script>
</body>
</html>